package nesemulator;

import com.nes.processor.ALU;
import com.nes.rom.Rom;
import com.nes.rom.RomReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author sad
 */
public class NesEmulator {

    public static void main(String[] args) throws IOException {
        //RomReader romreader=new RomReader();
        //Rom rom=romreader.createRom(new File("d:/rr.nes"));
        //Rom rom=romreader.createRom(new File("d:/Battle City.nes"));
        String[] lines = readLines();
        testAlu(readCode(), lines);
    }

    protected static void testAlu(byte[] b, String[] lines) throws IOException {
        FileWriter writer = null;
        writer = new FileWriter("D:\\log.txt", false);
        ALU alu = new ALU();
        alu.getMemory().setValue((byte) 0xA9, 0xA9A9);
        alu.getMemory().setValue((byte) 0xFF, 0x4015);
        alu.getMemory().setValue((byte) 0xff, 0x4004);
        alu.getMemory().setValue((byte) 0xff, 0x4005);
        alu.getMemory().setValue((byte) 0xff, 0x4006);
        alu.getMemory().setValue((byte) 0xFF,0x4007);
        try {
            alu.getMemory().setBytes(b, 0xc000);
        } catch (Exception ex) {
        }

        alu.setPc(0xC000);
        for (int i = 0; i < 8991; i++) {
//            writer.append(decoded);
//            writer.append(System.lineSeparator());
//            writer.flush();
//            if (!lines[i].equals(decoded)) {
//                System.err.println("Error: line №" + (i + 1));
//                System.err.println("Expected:" + lines[i]);
//                System.err.println("Actual  :" + decoded);
//                //return;
//            }

            alu.executeCommand();
        }

        writer.close();
    }

    private static byte[] readCode() {
        byte[] actualBytes;
        try {
            try (InputStream stream = NesEmulator.class.getResourceAsStream("/com/nes/resources/nestest.nes")) {
                byte[] bytes = IOUtils.toByteArray(stream);
                actualBytes = Arrays.copyOfRange(bytes, 16, bytes.length);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return actualBytes;
    }

    private static String[] readLines() {
        String[] lines;
        try {
            try (InputStream stream = NesEmulator.class.getResourceAsStream("/com/nes/resources/nestest.log")) {
                lines = IOUtils.readLines(stream).toArray(new String[0]);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return lines;
    }
}
